function isDate(date,format) {
  if(!date) return false;
  if(!format) format = 'FR';

  switch(format){
    case'FR':
      RegExpformat = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/([2][0]|[1][9])\d{2})$/; break;
    case'US':
      RegExpformat = /^([2][0]|[1][9])\d{2}\-([0]\d|[1][0-2])\-([0-2]\d|[3][0-1])$/; break;
    case'SHORTFR':
      RegExpformat = /^([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/\d{2}$/; break;
    case'SHORTUS':
      RegExpformat = /^\d{2}\-([0]\d|[1][0-2])\-([0-2]\d|[3][0-1])$/; break;
  }

  return RegExpformat.test(date);
}

//HoNT added: Allow to check a date in DD/MM/YYYY format
function isValidDate(dateStr) {
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables

//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

// To require a 4 digit year entry, use this line instead:
 var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
//alert("Date is not in a valid format.")
return false;
}
day = matchArray[1]; // parse date into variables
month = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
//alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
//alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
//alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
}
return true;  // date is valid
}

function searchboxOnFocus(input) {
	input.value = "";
	//input.style.color = "inherit";
}
function searchboxOnBlur(input, text) {
	if (input.value.length == 0) {
		input.value = text;
		input.style.color = "#777";
	}
}

function changeLanguage(language) {
	var url = document.location.href;
	if (url.indexOf("?l=") >= 0) {
		url = url.substring(0, url.indexOf("?l=")) + "?l=" + language;
//		url = url+"&l=" + language;
	}if (url.indexOf("&l=") >= 0) {
		url = url.substring(0, url.indexOf("&l=")) + "&l=" + language;

	} else if (url.indexOf("?") >= 0){
		url = url + "&l=" + language;
	} else {
		url = url + "?l=" + language;
	}
	document.location = url;
}

function changeTopmovers(target, anotherTarget, iNo){
	for (var i = 1; i < 6; i++ ) {
		if(!( i == iNo)) {
			obj=document.getElementById(target+String(i));
			obj.style.display = "none";
		} else {
			obj=document.getElementById(target+String(i));
			obj.style.display = "inline";
		}
	}
	for (var j = 1; j < 6; j++ ) {
		obj=document.getElementById(anotherTarget+String(j));
		obj.style.display = "none";
	}
}

function changeTopmoversIndustry(target, iNo){
	for (var i = 1; i < 6; i++ ) {
		if(!( i == iNo)) {
			obj=document.getElementById(target+String(i));
			obj.style.display = "none";
		} else {
			obj=document.getElementById(target+String(i));
			obj.style.display = "inline";
		}
	}
}


// JavaScript Document
function LTrim(val) {
	while (val.charAt(0) == " ") {
		val = val.substring(1, val.length);
	}
	return val;
}

function RTrim(val) {
	while (val.charAt(val.length - 1) == " ") {
		val = val.substring(0, val.length - 1);
	}
	return val;
}

function TrimString(str) {
	return LTrim( RTrim(str) );
}

function Trim(fld) {
	var ret = fld.value;
	ret = LTrim(ret);
	ret = RTrim(ret);
	while (ret.search(/  /g) > 0) {
		ret = ret.replace(/  /g, " ");
	}
	return ret;
}

function IsNumeric(sText) {
var ValidChars = "0123456789.,";
var IsNumber=true;
var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) {
  Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
	 IsNumber = false;
	 }
  }
return IsNumber;
}

function check_zero(strObjName,strContent){
 if(TrimString(strObjName.value) == ""){
   //alert("Please enter " + strContent  + " !");
   strObjName.focus();
   return true;
	} else {
  return false;
 }
}

function pp_getElementByName(name) {
	return document.getElementsByName(name)[0];
}
function selectOption(select, option) {
    var i;
    for (i = 0; i < select.options.length; i++) {
        if (select.options[i].value == option) {
            select.options[i].selected = true;
            break;
        }
    }
}

function getImageData(url, symbol, index,urla) {
	document.getElementById("summaryChart").src = url;

	document.getElementById("summaryChartHref").href = urla + symbol;
      if(index == '1') {
	    changeTopmovers('topmovers'+index, 'topmovers2', 1);
      } else {
          changeTopmovers('topmovers'+index,  'topmovers1', 1);
      }


	/*if(symbol=='HOSE')
	{
		window.document.getElementById('HOSE').style.display = "";
		window.document.getElementById('HOSE').style.visibility = "visible";
		window.document.getElementById('HASTC').style.display = "none";
		window.document.getElementById('HASTC').style.visibility = "hidden";
	}
	if(symbol=='HASTC')
	{
		window.document.getElementById('HASTC').style.display = "";
		window.document.getElementById('HASTC').style.visibility = "visible";
		window.document.getElementById('HOSE').style.display = "none";
		window.document.getElementById('HOSE').style.visibility = "hidden";
	}*/
	//var request = getXMLHTTPRequest();
	//var response = getServerText(url, request);
}

function getXMLHTTPRequest() {
	try {
		req = new XMLHttpRequest();
	}
	catch (err1) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (err2) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (err3) {
				req = false;
			}
		}
	}
	return req;
}

function getServerText(url, request) {
	request.open("GET", url, true);
	request.onreadystatechange = function () {
		callBack(request);
	};
	request.send(null);
}

function callBack(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
			var mytext = request.responseText;
			//document.getElementById("summaryChart").src = request.responseXML;
		}
	} else {
		//document.getElementById("summaryChart").src = "";
	}
}

// For market
function getServerDataForMarket(url, request) {

	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackDataForMarket(request);
	};
	request.send(null);
}

function callBackDataForMarket(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var xmlDomForMarket = null;
            var priceArrayMarket = new Array();
            var volArrayMarket = new Array();
            var endDateMarket = new Date();
            var market = null;
            var flags = new Array();
			 xmlDomForMarket = getXML(request);
            //alert(request.responseText);
			if(xmlDomForMarket == null) {
			    return;
			}

			var listVolNodeForMarket = selectNodeList(xmlDomForMarket, "/market/volume/vol-node");
			for (var i = 0; i < listVolNodeForMarket.length; i++) {
				if (listVolNodeForMarket[i].firstChild != null) {
                 	if(volArrayMarket.length < 500){
                 	volArrayMarket.push(listVolNodeForMarket[i].firstChild.nodeValue);
                 	}
                 } else {
                 	volArrayMarket.push(null);
                 }
                 //alert(listVolNodeForMarket[i].firstChild.nodeValue);
            }

            var listPriceNodeForMarket = selectNodeList(xmlDomForMarket, "/market/price/price-node");
			for (var i = 0; i < listPriceNodeForMarket.length; i++) {
				if (listPriceNodeForMarket[i].firstChild) {
                 	if(priceArrayMarket.length < 500){
                 	priceArrayMarket.push(listPriceNodeForMarket[i].firstChild.nodeValue);
                 	}
                 } else {
                 	priceArrayMarket.push(null);
                 }
                 //alert(listPriceNodeForMarket[i].firstChild.nodeValue);
            }

			if (priceArrayMarket.length <=0) {
			    return;
            }
            var infoNodeForMarket = selectNodeList(xmlDomForMarket, "/market/info");
            var marketId = infoNodeForMarket[0].getAttribute("id");
            var marketName = infoNodeForMarket[0].getAttribute("name");
            var marketSymbol = infoNodeForMarket[0].getAttribute("symbol");
            var year = infoNodeForMarket[0].getAttribute("year");
            var month = infoNodeForMarket[0].getAttribute("month");
            var day = infoNodeForMarket[0].getAttribute("day");
            //alert(marketId + " " + marketName + " " + marketSymbol);
            //alert(year + " " + month + " " + day);
            market = new Company(2, marketSymbol, marketName, marketId);
            endDateMarket.setFullYear(year, month - 1, day);
              // tickets
            var listNodeForTicket = selectNodeList(xmlDomForMarket, "/market/tickets/ticket");
			for (var i = 0; i < listNodeForTicket.length; i++) {
                 var id = listNodeForTicket[i].getAttribute("id");
                 var createdDate = listNodeForTicket[i].getAttribute("createdDate");
                 var date = new Date();
                 var year = createdDate.substring(0,4);
                 var month = createdDate.substring(5,7);
                 var day =createdDate.substring(8,10);
                 //date.setFullYear(year, month - 1, day);
                 date.setFullYear(year, month - 1, day);
                 var flagObject = new Flag(0, id , date, i%26);
                 flags.push(flagObject);
            }
            var dataObj = new DataObj(market.id, endDateMarket, priceArrayMarket, volArrayMarket, flags);
            companies.push(market);
            dataObjs.push(dataObj);
			addChart(companies.length -1);
    		renderCompareTable();
		}
	} else {
		//alert("Can not connect to server successfully");
	}
}



// For industry
function getServerDataForIndustry(url, request) {
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackDataForIndustry(request);
	};
	request.send(null);
}

function callBackDataForIndustry(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var priceArrayIndustry = new Array();
            var volArrayIndustry = new Array();
             var flags = new Array();
            var xmlDomForIndustry = null;
            var endDateIndustry = new Date();
            var industry = null;
			xmlDomForIndustry = getXML(request);
            //alert(request.responseText);
			if(xmlDomForIndustry == null){
				return;
			}
			var listVolNodeForIndustry = selectNodeList(xmlDomForIndustry, "/industry/volume/vol-node");
			for (var i = 0; i < listVolNodeForIndustry.length; i++) {
				if (listVolNodeForIndustry[i].firstChild != null) {
                 	volArrayIndustry.push(listVolNodeForIndustry[i].firstChild.nodeValue);
                 } else {
                 	volArrayIndustry.push(null);
                 }
             //   alert(listVolNodeForIndustry[i].firstChild.nodeValue);
            }

            var listPriceNodeForIndustry = selectNodeList(xmlDomForIndustry, "/industry/price/price-node");
			for (var i = 0; i < listPriceNodeForIndustry.length; i++) {
				if (listPriceNodeForIndustry[i].firstChild != null) {
                 	priceArrayIndustry.push(listPriceNodeForIndustry[i].firstChild.nodeValue);
                 } else {
                 	priceArrayIndustry.push(null);
                 }
                 //alert(listPriceNodeForIndustry[i].firstChild.nodeValue);
            }

			if(	priceArrayIndustry.length <= 0) {
				return;
			}
            var infoNodeForIndustry = selectNodeList(xmlDomForIndustry, "/industry/info");
            var industryId = infoNodeForIndustry[0].getAttribute("id");
            var industryName = infoNodeForIndustry[0].getAttribute("name");
            var industrySymbol = infoNodeForIndustry[0].getAttribute("symbol");
            var year = infoNodeForIndustry[0].getAttribute("year");
            var month = infoNodeForIndustry[0].getAttribute("month");
            var day = infoNodeForIndustry[0].getAttribute("day");
            //alert(year + " " + month + " " + day);
            //alert(industryId + industryName + industrySymbol);
            industry = new Company(1, industrySymbol, industryName, industryId);
            endDateIndustry.setFullYear(year, month - 1 , day);
             // tickets
            var listNodeForTicket = selectNodeList(xmlDomForIndustry, "/industry/tickets/ticket");
			for (var i = 0; i < listNodeForTicket.length; i++) {
                 var id = listNodeForTicket[i].getAttribute("id");
                 var createdDate = listNodeForTicket[i].getAttribute("createdDate");
                 var date = new Date();
                 var year = createdDate.substring(0,4);
                 var month = createdDate.substring(5,7);
                 var day =createdDate.substring(8,10);
                 //date.setFullYear(year, month - 1, day);
                 date.setFullYear(year, month - 1, day);
                 var flagObject = new Flag(0, id , date, i%26);
                 flags.push(flagObject);
            }

            var dataObj = new DataObj(industry.id, endDateIndustry, priceArrayIndustry, volArrayIndustry, flags);
            companies.push(industry);
            dataObjs.push(dataObj);
			addChart(companies.length - 1);
			//addChart(companies.length - 2);
    		renderCompareTable();
		}
	} else {
		//alert("Can not connect to server successfully");
	}
}

// For company
function getServerDataForCompany(url, request) {
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackDataForCompany(request);
	};
	request.send(null);
}

function callBackDataForCompany(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var priceArrayCompany = new Array();
            var volArrayCompany = new Array();
            var flags = new Array();
            var xmlDomForCompany = null;
            var endDateCompany = new Date();
            var company = null;
			xmlDomForCompany = getXML(request);
            //alert(request.responseText);
			if(xmlDomForCompany == null) return;
			var listVolNodeForCompany = selectNodeList(xmlDomForCompany, "/company/volume/vol-node");
			for (var i = 0; i < listVolNodeForCompany.length; i++) {
				if (listVolNodeForCompany[i].firstChild != null) {
                 	volArrayCompany.push(listVolNodeForCompany[i].firstChild.nodeValue);
                } else {
                	volArrayCompany.push(null);
                }
                 //alert(listVolNodeForcompany[i].firstChild.nodeValue);
            }

            var listPriceNodeForCompany = selectNodeList(xmlDomForCompany, "/company/price/price-node");
			for (var i = 0; i < listPriceNodeForCompany.length; i++) {
				if (listPriceNodeForCompany[i].firstChild != null) {
                 	priceArrayCompany.push(listPriceNodeForCompany[i].firstChild.nodeValue);
                 } else {
                 	priceArrayCompany.push(null);
                 }
                 //alert(listPriceNodeForcompany[i].firstChild.nodeValue);
            }
            if (priceArrayCompany.length <=0) {
				return;
            }
            var infoNodeForCompany = selectNodeList(xmlDomForCompany, "/company/info");
            var companyId = infoNodeForCompany[0].getAttribute("id");
            var companyName = infoNodeForCompany[0].getAttribute("name");
            var companySymbol = infoNodeForCompany[0].getAttribute("symbol");
            var year = infoNodeForCompany[0].getAttribute("year");
            var month = infoNodeForCompany[0].getAttribute("month");
            var day = infoNodeForCompany[0].getAttribute("day");
            //alert(year + " " + month + " " + day);
            //alert(companyId + companyName + companySymbol);
            endDateCompany.setFullYear(year, month - 1, day);
            company = new Company(0, companySymbol, companyName, companyId);

            // tickets
            var listNodeForTicket = selectNodeList(xmlDomForCompany, "/company/tickets/ticket");
			for (var i = 0; i < listNodeForTicket.length; i++) {
                 var id = listNodeForTicket[i].getAttribute("id");
                 var createdDate = listNodeForTicket[i].getAttribute("createdDate");
                 var date = new Date();
                 var year = createdDate.substring(0,4);
                 var month = createdDate.substring(5,7);
                 var day =createdDate.substring(8,10);
                 //date.setFullYear(year, month - 1, day);
                 date.setFullYear(year, month - 1, day);
                 var flagObject = new Flag(0, id , date, i%26);
                 flags.push(flagObject);
            }

            var dataObj = new DataObj(company.id,endDateCompany,priceArrayCompany,volArrayCompany, flags);
            companies.push(company);
            dataObjs.push(dataObj);
			addChart(companies.length -1);
    		renderCompareTable();
		}
	} else {
		//alert("Can not connect to server successfully");
	}
}

// For company_Tickets

function getTicketsForChartCompany(url, request) {
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackTicketsForChartCompany(request);
	};
	request.send(null);
}

function callBackTicketsForChartCompany(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            xmlDomForTickets = getXML(request);
            //alert(request.responseText);
			var listNodeForTicket = selectNodeList(xmlDomForTickets, "/company/tickets/ticket");
			for (var i = 0; i < listNodeForTicket.length; i++) {
                 var id = listNodeForTicket[i].getAttribute("id");
                 var createdDate = listNodeForTicket[i].getAttribute("createdDate");
                 var flagObject = new Flag(0, id , new Date(createdDate),i%26);
                 flags.push(flagObject);
            }
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}




// For list_Industry

function getListIndustryForChart(url, request) {
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackListIndustryForChart(request);
	};
	request.send(null);
}

function callBackListIndustryForChart(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            xmlDomForListIndustry = getXML(request);
            //alert(request.responseText);
			var listNodeForListIndustry = selectNodeList(xmlDomForListIndustry, "/industry/code");
			for (var i = 0; i < listNodeForListIndustry.length; i++) {
                if (listNodeForListIndustry[i].firstChild != null) {
                 	listIndustryToCheck.push(listNodeForListIndustry[i].firstChild.nodeValue);
                } else {
                	listNodeForListIndustry.push(null);
                }
            }
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

// For Industry_listCompany
function getListCompanyOfIndustry(url) {
	request = getXMLHTTPRequest();
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackListCompanyOfIndustry(request);
	};
	request.send(null);
}

function callBackListCompanyOfIndustry(request) {

	if (request.readyState == 4) {
		if (request.status == 200) {
            var main = getElem("listCompany");
            main.innerHTML = "";
            var node = document.createElement("div");
            node.innerHTML =  request.responseText;
            main.appendChild(node);
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

//For Advertisement
//@author: anhhc

//change advertisement order
function ChangeAdvertisementOrder(url) {
	var request = getXMLHTTPRequest();
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackChangeAdvertisementOrder(request);
	};
	request.send(null);
}

function callBackChangeAdvertisementOrder(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var main = document.getElementById("listAdvertisements");
            main.innerHTML = "";
            var node = document.createElement("div");
            node.innerHTML =  request.responseText;
            main.appendChild(node);
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

//show advertisement
//bottom left
function ShowAdvertisementBottomLeft(url) {
	var request = getXMLHTTPRequest();
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackShowAdvertisementBottomLeft(request);
	};
	request.send(null);
}

function callBackShowAdvertisementBottomLeft(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {

            var main = document.getElementById("bottom-left-advertisements");
            main.innerHTML = "";
            var node = document.createElement("div");
            node.innerHTML =  request.responseText;
            main.appendChild(node);
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

//bottom right
function ShowAdvertisementBottomRight_(url) {
	var request = getXMLHTTPRequest();
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackShowAdvertisementBottomRight(request);
	};
	request.send(null);
}

function ShowAdvertisementBottomRight(url) {
	new Ajax.Updater({success:"bottom-right-advertisements", failure:"bottom-right-advertisements"}, url, {evalScripts:true});
}
function callBackShowAdvertisementBottomRight(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var main = document.getElementById("bottom-right-advertisements");
            main.innerHTML = "";
            var node = document.createElement("div");
            node.style.position="inherit";
            node.innerHTML =  request.responseText;
            main.appendChild(node);
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

function ShowAdvertisement(url, divId) {
	new Ajax.Updater({success:divId, failure:divId}, url, {evalScripts:true});
}

//news details
function ShowAdvertisementNewsDetails(url) {
	var request = getXMLHTTPRequest();
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackShowAdvertisementNewsDetails(request);
	};
	request.send(null);
}

function callBackShowAdvertisementNewsDetails(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var main = document.getElementById("news-details-advertisements");
            main.innerHTML = "";
            var node = document.createElement("div");
            node.style.width='300px';
            node.style.align='center';
            node.innerHTML =  request.responseText;
            main.appendChild(node);
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

//bond details
function ShowAdvertisementBond(url) {
	var request = getXMLHTTPRequest();
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackShowAdvertisementBond(request);
	};
	request.send(null);
}

function callBackShowAdvertisementBond(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var main = document.getElementById("bond-advertisements");
            main.innerHTML = "";
            var node = document.createElement("div");
            node.innerHTML =  request.responseText;
            main.appendChild(node);
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

//change rolling advertisement
function ChangeRollingAdvertisementSpeed(url) {
	var request = getXMLHTTPRequest();
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackChangeRollingAdvertisementSpeed(request);
	};
	request.send(null);
}

function callBackChangeRollingAdvertisementSpeed(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var main = document.getElementById("rolling_speed");
            main.innerHTML = "";
            var node = document.createElement("div");
            node.innerHTML =  request.responseText;
            main.appendChild(node);
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

function getXML (response) {
  var contentType = response.getResponseHeader("Content-Type");
  if (contentType) {
    if (contentType.match(/^text\/xml;/i)) {
      var xml;
      if (!hasNativeXPathSupport()) {
        xml = xmlParse(response.responseText);
      } else {
        xml = response.responseXML;
      }
      if (xml.parseError && xml.parseError.errorCode != 0) { // for IE
        return null;
      }
      if (xml.documentElement.tagName == "parsererror") { // for Gecko
        return null;
      }
      if (selectString(xml, "/fault")) {
       return null;
      }
      return xml;
    } else {
      return null;
    }
  } else { // server down
    return null;
  }
};

function selectNode(context, expr) {
  if (context.documentElement) {
    var xml = context;
    context = context.documentElement;
  } else {
    var xml = context.ownerDocument;
  }
  if (!hasNativeXPathSupport()) {
    // This is for all browsers with no built in XPath support.
    var compExpr = xpathParse(expr);
    var node = compExpr.evaluate(new ExprContext(context));
    return (node.value[0]);
  } else if (window.ActiveXObject) {
    xml.setProperty("SelectionLanguage", "XPath");
    var node = context.selectSingleNode(expr);
    return node;
  } else if (xml.evaluate) {
    return xml.evaluate(expr, context, xml.createNSResolver(context),
        XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  } else {
    // Should never get here.
  }
  return null;
};

function selectNodeList (context, expr) {
  if (context.documentElement) {
    var xml = context;
    context = context.documentElement;
  } else {
    var xml = context.ownerDocument;
  }
  if (!hasNativeXPathSupport()) {
    // This is for all browsers with no built in XPath support
    var compExpr = xpathParse(expr);
    var iterator = compExpr.evaluate(new ExprContext(context));
    var list = iterator.nodeSetValue();
    return (list);
  } else if (window.ActiveXObject) {
    xml.setProperty("SelectionLanguage", "XPath");
    var iterator = context.selectNodes(expr);
    var list = new Array();
    while (true) {
      var node = iterator.nextNode();
      if (node) {
        list.push(node);
      } else {
        break;
      }
    }
    return list;
  } else if (xml.evaluate) {
    var iterator = xml.evaluate(expr, context, xml.createNSResolver(context),
        XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    var list = new Array();
    while(true) {
      var node = iterator.iterateNext();
      if (node) {
        list.push(node);
      } else {
        break;
      }
    }
    return list;
  } else {
    // Should never get here.
  }
  return null;
};


function hasNativeXPathSupport (xml) {
  var result = false;
  // An override to make debugging easier.  This override will enable the
  // Google XPath/XSLT library for all browsers
  if (window.overrideNativeXPath) {
    return (result);
  }
  if (!xml) {
    if (document.implementation &&
        document.implementation.createDocument) {
      xml = document.implementation.createDocument("", "", null);
    }
  }
  if (window.ActiveXObject) {
    result = true;
  } else if (xml.evaluate) {
    result = true;
  }
  return (result);
};

function selectString (context, expr) {
  if (context.documentElement) {
    var xml = context;
    context = context.documentElement;
  } else {
    var xml = context.ownerDocument;
  }
  if (!hasNativeXPathSupport()) {
    // This is for all browsers with no built in XPath support
    var compExpr = xpathParse(expr);
    var node = compExpr.evaluate(new ExprContext(context));
    debug("selectString: expr=" + expr + " done.");
    return (node.stringValue());
  } else if (window.ActiveXObject) {
    xml.setProperty("SelectionLanguage", "XPath");
    var node = context.selectSingleNode(expr);
    return node != null ? node.text : null;
  } else if (xml.evaluate) {
    return xml.evaluate(expr, context, xml.createNSResolver(context),
        XPathResult.STRING_TYPE, null).stringValue;
  } else {
    // Should never get here.
  }
  return null;
};

/****************************************************************************************
 *SECTOR
 ***************************************************************************************/

function getServerDataForSector(url, request) {
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackDataForSector(request);
	};
	request.send(null);
}

function callBackDataForSector(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
            var priceArraySector = new Array();
            var volArraySector = new Array();
             var flags = new Array();
            var xmlDomForSector = null;
            var endDateSector = new Date();
            var sector = null;
			xmlDomForSector = getXML(request);
            //alert(request.responseText);
			if(xmlDomForSector == null){
				return;
			}
			var listVolNodeForSector = selectNodeList(xmlDomForSector, "/sector/volume/vol-node");
			for (var i = 0; i < listVolNodeForSector.length; i++) {
				if (listVolNodeForSector[i].firstChild != null) {
                 	volArraySector.push(listVolNodeForSector[i].firstChild.nodeValue);
                 } else {
                 	volArraySector.push(null);
                 }
             //   alert(listVolNodeForSector[i].firstChild.nodeValue);
            }

            var listPriceNodeForSector = selectNodeList(xmlDomForSector, "/sector/price/price-node");
			for (var i = 0; i < listPriceNodeForSector.length; i++) {
				if (listPriceNodeForSector[i].firstChild != null) {
                 	priceArraySector.push(listPriceNodeForSector[i].firstChild.nodeValue);
                 } else {
                 	priceArraySector.push(null);
                 }
                 //alert(listPriceNodeForSector[i].firstChild.nodeValue);
            }

			if(	priceArraySector.length <= 0) {
				return;
			}
            var infoNodeForSector = selectNodeList(xmlDomForSector, "/sector/info");
            var sectorId = infoNodeForSector[0].getAttribute("id");
            var sectorName = infoNodeForSector[0].getAttribute("name");
            var sectorSymbol = infoNodeForSector[0].getAttribute("symbol");
            var year = infoNodeForSector[0].getAttribute("year");
            var month = infoNodeForSector[0].getAttribute("month");
            var day = infoNodeForSector[0].getAttribute("day");
            //alert(year + " " + month + " " + day);
            //alert("sectorId= " + sectorId + ", sectorName= " + sectorName + ", sectorSymbol= " + sectorSymbol);
            sector = new Company(3, sectorSymbol, sectorName, sectorId);
            endDateSector.setFullYear(year, month - 1 , day);
             // tickets
            var listNodeForTicket = selectNodeList(xmlDomForSector, "/sector/tickets/ticket");
			for (var i = 0; i < listNodeForTicket.length; i++) {
                 var id = listNodeForTicket[i].getAttribute("id");
                 var createdDate = listNodeForTicket[i].getAttribute("createdDate");
                 var date = new Date();
                 var year = createdDate.substring(0,4);
                 var month = createdDate.substring(5,7);
                 var day =createdDate.substring(8,10);
                 //date.setFullYear(year, month - 1, day);
                 date.setFullYear(year, month - 1, day);
                 var flagObject = new Flag(0, id , date, i%26);
                 flags.push(flagObject);
            }

            var dataObj = new DataObj(sector.id, endDateSector, priceArraySector, volArraySector, flags);
            companies.push(sector);
            dataObjs.push(dataObj);
			addChart(companies.length - 1);
			//addChart(companies.length - 2);
    		renderCompareTable();
		}
	} else {
		//alert("Can not connect to server successfully");
	}
}

// For list_sector
function getListSectorForChart(url, request) {
	request.open("POST", url, true);
	request.onreadystatechange = function () {
		callBackListSectorForChart(request);
	};
	request.send(null);
}

function callBackListSectorForChart(request) {
	if (request.readyState == 4) {
		if (request.status == 200) {
			//alert(request.responseText);
            xmlDomForListSector = getXML(request);
			var listNodeForListSector = selectNodeList(xmlDomForListSector, "/sector/code");
			for (var i = 0; i < listNodeForListSector.length; i++) {
                if (listNodeForListSector[i].firstChild != null) {
                 	listSectorToCheck.push(listNodeForListSector[i].firstChild.nodeValue);
                } else {
                	listNodeForListSector.push(null);
                }
            }
        }
	} else {
		//alert("Can not connect to server successfully");
	}
}

function removeAllChar(strInput, strFind, strRep){
	idx = strInput.indexOf(strFind);
	while(idx != -1){
		strInput = strInput.replace(strFind, strRep);
		idx = strInput.indexOf(strFind);
	}
	return strInput;
}

function popupWindowCenter(url, title, width, height) {
	var left = (screen.width/2)-(width/2);
	var top = (screen.height/2)-(height/2);
	var targetWin = window.open (url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+width+', height='+height+', top='+top+', left='+left);
}

function popupWindow(url, title) {
	var targetWin = window.open (url);
	targetWin.opener = top;
	targetWin.focus();
}

function isFloat(x) {
	return (x == parseFloat(x));
}

function doOnKeyPress(evt) {
	evt = (evt) ? evt : ((window.event) ? event : null);
	if (evt) {
		var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
		if (elem) {
			var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
			/**
			 * 8: Backspace, 9:	Tab, 37: <-, 39: ->, 46: Del
			 */
			if((charCode < 48 || charCode > 57) && charCode != 8 && charCode != 9 && charCode != 37 && charCode != 39 && charCode != 46) {
				var ie = (navigator.appName.indexOf ("Microsoft") != -1) ? 1 : 0;
				if(ie == 0) {
					evt.preventDefault();
				}
				evt.returnValue = false;
			}
		}
    }
}

function calYear(x) {
	if(x < 1000)
		return x + 1900;
	return x;
}

function changeDateToEnFormat(strDate) {
	var dd = strDate.substring(0, 2);
	var mm = strDate.substring(3, 5);
	var yy = strDate.substring(6, 10);
	return mm + "/" + dd+ "/" + yy;
}

/**
 * Mouse move on TR in the finance data
 */
function onMouseOver(id) {
	obj = document.getElementById(id);
	if(obj) {
		obj.bgColor = "#efe7cf"; //"#E6FECF"; //"#EEFEE0"; //"#DDFDD5"; //"#DCFDBD";
	}
	obj = null;
}

function onMouseout(id) {
	obj = document.getElementById(id);
	if(obj) {
		obj.bgColor = "#FFFFFF";
	}
	obj = null;
}
function isBefore(date1, date2) {
	var splitFromDate = date1.split('/');
    var splitToDate = date2.split('/');
    var dt1   = parseInt(splitFromDate[0],10);
    var mon1  = parseInt(splitFromDate[1],10)-1;
    var yr1   = parseInt(splitFromDate[2],10);
    var dt2   = parseInt(splitToDate[0],10);
    var mon2  = parseInt(splitToDate[1],10)-1;
    var yr2   = parseInt(splitToDate[2],10);
    var date1 = new Date(yr1, mon1, dt1);
    var date2 = new Date(yr2, mon2, dt2);
    if(date1 > date2){
    	return false;
    } else {
    	return true;
    }
}